<template>
  <div>
    <page-header title="检查清单">
      <n-button type="primary" @click="handleClickAdd">新增</n-button>
    </page-header>
    <div class="mt-[16px]">
      <n-grid x-gap="12" :cols="4">
        <n-gi>
          <n-input
            placeholder="请输入检查清单名称"
            v-model:value="paginationResult.name"
            @keyup.enter="handleSearch"
            clearable
          />
        </n-gi>
      </n-grid>
      <div class="mt-[16px]"></div>
      <BasicTable
        :table-props="tableResult"
        :columns="columns"
        :pagination-props="paginationResult"
        :style="{ height: `66vh` }"
      />
    </div>
  </div>
</template>
<script setup lang="ts">
import { h, onMounted } from "vue";
import { useRouter } from "vue-router";
import { debounce } from "lodash-es";
import { NButton, NIcon } from "naive-ui";
import { useTableHook } from "@/components/normal/basicTable/useTableHook";
import { Trash, CreateOutline } from "@vicons/ionicons5";
import {
  getCheckListList,
  deleteCheckListById,
} from "@/api/checkList/checkList.api";
import {
  CHECKLIST_ADD_PAGE,
  CHECKLIST_DETAIL_PAGE,
} from "@/router/routerNames/index";

const columns = [
  {
    title: "#",
    type: "index",
    key: "key",
    render: (_: any, index: number) => {
      return `${index + 1}`;
    },
  },
  {
    title: "检查清单名称",
    key: "name",
  },
  {
    title: "最新更新时间",
    key: "updateTime",
  },
  {
    title: "操作",
    key: "actions",
    align: "right",
    render: (row: any) => {
      return [
        h(
          NButton,
          {
            size: "small",
            secondary: true,
            class: "mr-2",
            onClick: () => handleClickDetail(row),
          },
          {
            icon: () =>
              h(NIcon, null, {
                default: () => h(CreateOutline),
              }),
          }
        ),
        h(
          NButton,
          {
            size: "small",
            type: "error",
            secondary: true,
            onClick: () => handleDelete(row.id),
          },
          {
            icon: () =>
              h(NIcon, null, {
                default: () => h(Trash),
              }),
          }
        ),
      ];
    },
  },
];

const router = useRouter();

const { tableResult, paginationResult, getDataList } = useTableHook<any>({
  api: getCheckListList,
  queryForm: {
    name: "",
  },
  likeKeys: ["name"],
});

const handleSearch = debounce(function () {
  paginationResult.page = 1;
  getDataList();
}, 200);

const handleClickDetail = (payload: any) => {
  router.push({
    name: CHECKLIST_DETAIL_PAGE.NAME,
    params: {
      id: payload.id,
    },
  });
};

const handleClickAdd = () => {
  router.push({
    name: CHECKLIST_ADD_PAGE.NAME,
  });
};

const handleDelete = (checkListId: string) => {
  deleteCheckListById(checkListId).then(() => {
    getDataList();
  });
};

const init = () => {
  getDataList();
};

onMounted(() => {
  init();
});
</script>
